package com.quick.im.manager.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quick.im.common.base.BaseResponse;
import com.quick.im.common.constant.ImRedisKey;
import com.quick.im.common.entity.User;
import com.quick.im.common.enums.GlobalExceptionEnum;
import com.quick.im.common.util.RedisUtils;
import com.quick.im.manager.interfaces.IUserService;
import com.quick.im.manager.mapper.UserMapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;


/**
 * 用户信息表(User) 服务实现类
 *
 * @author xhh
 * @since 2025-01-23
 */
@Service("UserServiceImpl")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Setter(onMethod_ = @Autowired)
    private UserMapper dataMapper;

    @Override
    public void saveUser(User request) throws Exception {
        UUID uuid = UUID.randomUUID();
        request.setUid(uuid.toString());
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        LambdaQueryWrapper<User> eq = queryWrapper.eq(User::getMobile, request.getMobile());
        User res = getOne(eq);

        if (res != null)
            throw new Exception("手机号已注册！");
        save(request);

    }

    @Override
    public void deleteUserById(Integer id) {
        removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User updateUser(User request) {
        updateById(request);
        return request;
    }

    @Override
    public Page<User> listUser(User request) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        Page<User> page = new Page<>(request.getPage(), request.getPageSize());
        return page(page, queryWrapper);
    }

    @Override
    public BaseResponse<User> getUserById(Integer id) {

        return BaseResponse.success();
    }

    @Override
    public User login(User request)  {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        LambdaQueryWrapper<User> eq = queryWrapper.eq(User::getMobile, request.getMobile()).eq(User::getPassword,request.getPassword());
        User res = getOne(eq);
        if (res == null){
            return null;
        }
        // 生成token
        // 设置缓存，websocket登录使用
//        Object o = RedisUtils.set(ImRedisKey.TOKEN_USER_INFO + token,res);
        return res;
    }


}

